<?php

namespace ASW\Utility;

class Crypt
{
    /**
     * 字符串加密
     *
     * @param string $source
     * @param string $key
     *
     * @return string
     */
    public static function simpleEncrypt(string $source, string $key): string
    {
        if ($source == '') return '';
        if ($key == '') return base64_encode($source);
        $xor_str = self::strXor(md5($key), $source);
        return base64_encode($xor_str);
    }

    /**
     * 字符串异或
     *
     * @param string $key
     * @param string $string
     *
     * @return string
     */
    public static function strXor(string $key, string $string): string
    {
        $result = '';
        for ($i = 0; $i < strlen($string); $i++) {
            $xor    = $string[$i] ^ $key[$i % strlen($key)];
            $result .= ord($xor) > 0 ? $xor : $string[$i];
        }
        return $result;
    }

    /**
     * 字符串解密
     *
     * @param string $source
     * @param string $key
     *
     * @return string
     */
    public static function simpleDecrypt(string $source, string $key): string
    {
        if ($source == '') return '';
        $source = str_replace(' ', '+', $source);
        $source = base64_decode($source);

        if ($key == '') return $source;
        return self::strXor(md5($key), $source);
    }
}